package common

import (
	"fmt"
	"service/app/mode"
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func DbInit() (*gorm.DB, error) {
	// 判断运行环境
	logMode := logger.Info
	if !viper.GetBool("service.dev") {
		logMode = logger.Error
	}
	// dsn := "root:qq0233200@tcp(192.168.1.13:3306)/golang?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := viper.GetString("db.user") + ":" + viper.GetString("db.passwd") + "@tcp(" + viper.GetString("db.host") + ":" + viper.GetString("db.port") + ")/" + viper.GetString("db.database") + "?charset=utf8mb4&parseTime=True&loc=Local"
	fmt.Println("当前的运行环境mysql", viper.GetString("db.host"))
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		// 表设置
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logMode),
	})
	// 判断运行
	if err != nil {
		return nil, err
	}

	fmt.Printf("%v", viper.GetDuration("db.SetConnMaxLifetime"))
	// 运行数据库
	myDb, _ := db.DB()
	myDb.SetMaxOpenConns(viper.GetInt("db.SetMaxOpenConns"))
	myDb.SetMaxIdleConns(viper.GetInt("db.SetMaxIdleConns"))
	myDb.SetConnMaxLifetime(time.Hour)

	// 创建转移列表
	if err := db.AutoMigrate(&mode.Lz_user{}, &mode.Db_pm{}, &mode.Db_menu{}, &mode.Db_roles{},
		&mode.Db_apm{}, &mode.Db_cost{}); err != nil {
		return nil, err
	}
	return db, nil
}
